<?php

namespace app\api\controller;


use Throwable;
use think\facade\Db;
use think\facade\Config;
use app\common\model\User;
use app\common\controller\Frontend;
use app\admin\model\SubscribeOrder;
use app\admin\model\SubscribeRecord;
class Order extends Frontend{

    protected array $noNeedPermission = ['index','detail','qrcode','tradeno'];

    public function initialize(): void
    {
        parent::initialize();
        
    }
    public function index(){
        if($this->request->isPost()){
            $page = $this->request->post('page',1);
            $list = SubscribeOrder::withJoin('user','left')->where('subscribe_order.user_id',$this->auth->id)->where('subscribe_order.status',1)->page($page,10)->order('id desc')->select();
            $this->success('',$list,200);
        }
    }

    public function tradeno(){
        if($this->request->isPost()){
            $id = $this->request->post('id',0);
            $order =  SubscribeOrder::where('status',1)->where('out_trade_no',$id)->find();
            $this->success('',$order['id'],200);
        }
    }

    public function detail(){
        if($this->request->isPost()){
            $id = $this->request->post('id',0);
           $order =  SubscribeOrder::where('status',1)->where('id',$id)->find();
           $isopen = get_sys_config('is_open');
           if($isopen == 0 && $order->state==1){
            $order->state=2;
            $order->save();
           }
           $arr = $order->toArray();
           if($order->out_trade_type == 6){
            $arr['goods'] = SubscribeRecord::withJoin('stadium','left')->where('subscribe_record.order_id',$order->id)->where('subscribe_record.subscribe_type',1)->select();
            $arr['user'] = Db::name('User')->where('id',$arr['user_id'])->find();
           }
           $this->success('',$arr,200);
        }
    }

    public function qrcode(){
        if($this->request->isPost()){
            $id = $this->request->post('id',0);
            $order =  SubscribeOrder::where('status',1)->where('id',$id)->find();
            if($order['state'] > 2 && (time()-$order['update_time']) > 300 ){
                $this->error('已核销');
            }
            $text = 'O'.$order['id'].'U'.$order['user_id'];
            $this->success('',$text,200);
        }
    }
}